import { reactive, ref } from 'vue'
import { UnwrapNestedRefs } from '@vue/reactivity'
import { useHttpRequest } from '@/api/chunfeng/apiRequest'
import { QueryUnitData, UnitData } from '@/api/chunfeng/unit/interfaces'
import { useUnitApi } from '@/api/chunfeng/unit'
import { Form } from 'ant-design-vue'

const { executeQueryRequest, executeCommandRequest } = useHttpRequest()
const { queryUnit, enableUnit, disableUnit } = useUnitApi()

export const useUnitQueryFunctions = () => {
  const unitDataSet = ref(Array<UnitData>())

  const paginationConfig = reactive({
    showSizeChanger: true,
  })

  const queryParams: UnwrapNestedRefs<QueryUnitData> = reactive({
    name: undefined,
    enabled: undefined,
  })

  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '状态',
      dataIndex: 'enabled',
      key: 'enabled',
      slots: { customRender: 'enabled' },
    },
    {
      title: '操作',
      key: 'action',
      slots: { customRender: 'action' },
    },
  ]

  const { resetFields } = Form.useForm(queryParams, reactive({}))

  function enable(uid: string) {
    executeCommandRequest(enableUnit(uid), {
      message: '单位启用成功',
      callback: () => {
        query()
      },
    })
  }

  function disable(uid: string) {
    executeCommandRequest(disableUnit(uid), {
      message: '单位停用成功',
      callback: () => {
        query()
      },
    })
  }

  function edit(uid: string) {}

  function reset() {
    resetFields()
  }

  function query() {
    unitDataSet.value.length = 0
    executeQueryRequest(queryUnit(queryParams), (results: UnitData[]) => {
      unitDataSet.value.push(...results)
    })
  }

  return {
    unitDataSet,
    queryParams,
    enable,
    disable,
    query,
    paginationConfig,
    columns,
    reset,
    edit,
  }
}
